package com.nine.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.nine.entity.MyReturn;
import com.nine.entity.PageSort;
import com.nine.entity.Userinfo;
import com.nine.service.DeptService;
import com.nine.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ：婷儿
 * @date ：Created in 2022/6/25 9:35
 * @description：userinfo表的控制层
 * @modified By：
 * @version:
 */
@RestController
@RequestMapping("userinfo")
public class UserinfoController extends ControllerFather{
    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    private DeptService deptService;

    MyReturn myReturn = new MyReturn();

    @RequestMapping("upload.do")
    @ResponseBody
    public MyReturn upload(MultipartFile xxx, HttpServletRequest request){
        //获取原始文件名
        String filename = xxx.getOriginalFilename();
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tFKaELot1rFRjaWPgXK";
        String accessKeySecret = "AcstN3JD2xjEMrScuG8dkl2vK4LXaY";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "fmcspace";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = UUID.randomUUID() + filename;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String src = "https://" + bucketName + "." + endpoint + "/" + objectName;

        Map map = new HashMap();
        map.put("src",src);
        myReturn.setCode(0);
        myReturn.setData(map);
        try {
            //原始文件

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(xxx.getBytes()));
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传字符串。
            ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return myReturn;
    }
    @RequestMapping("select.do")
    public MyReturn select(PageSort pageSort){
        Integer page = pageSort.getPage();
        int pageNew=(page-1)*pageSort.getLimit();
        pageSort.setPage(pageNew);
        List<Userinfo> userinfoList = userinfoService.select(pageSort);
        if (userinfoList!=null&&userinfoList.size()>0){
            myReturn.setData(userinfoList);
            myReturn.setCount(userinfoService.selectCount());
            return super.getSuccessResult(myReturn);
        }else{
            return super.getFailResult(myReturn);
        }
    }
    @RequestMapping("add.do")
    public MyReturn add(Userinfo userinfo){
        if(userinfo.getStatus()!=null){
            userinfo.setStatus("0");
        }else{
            userinfo.setStatus("1");
        }
        String login_name = userinfoService.selectUsername(userinfo.getLoginName());
        if (login_name!=null){
            myReturn.setCode(200);
            myReturn.setMsg("该用户名字已经被使用，请换一个用户名");
            return myReturn;
        }else {
            int add = userinfoService.add(userinfo);
            if (add > 0) {
                return super.getSuccessResult(myReturn);
            } else {
                return super.getFailResult(myReturn);
            }
        }
    }
    @RequestMapping("delete.do")
    public MyReturn delete(String[] userId){
        int delete = userinfoService.delete(userId);
        if (delete>0){
            return super.getSuccessResult(myReturn);
        }else{
            return super.getFailResult(myReturn);
        }
    }
    @RequestMapping("update.do")
    public MyReturn update(Userinfo userinfo){
        if(userinfo.getStatus()!=null){
            userinfo.setStatus("0");
        }else{
            userinfo.setStatus("1");
        }
        String s = userinfoService.selectUpdate(userinfo.getLoginName(), userinfo.getUserId());
        if(s!=null){
            myReturn.setCode(200);
            myReturn.setMsg("该用户名字已经被使用，请换一个用户名");
            return myReturn;
        }else{
            int update = userinfoService.update(userinfo);
            if(update>0){
                return super.getSuccessResult(myReturn);
            }else{
                return super.getFailResult(myReturn);
            }
        }
    }
    @RequestMapping("password.do")
    public MyReturn updatePassword(Userinfo userinfo){
        int i = userinfoService.updatePasswordInt(userinfo);
        if(i>0){
            return super.getSuccessResult(myReturn);
        }else{
            return super.getFailResult(myReturn);
        }
    }

    /**
     * @create by: Fmc
     * @description: 通过session域获取当前用户ID，并通过sql语句查找到该用户的信息
     * @create time: 2022/6/29 10:07
     * @return:
     */
    @RequestMapping("selectById.do")
    public MyReturn selectById(HttpSession session){
        Userinfo userInfo = (Userinfo) session.getAttribute("userInfo");
        Userinfo userinfo = userinfoService.selectById(userInfo.getUserId());
        myReturn.setCode(0);
        myReturn.setData(userinfo);
        return myReturn;
    }
    /**
     * @create by: Fmc
     * @description: 个人信息修改
     * @create time: 2022/6/29 18:08
     * @return:
     */
    @RequestMapping("updateOneself.do")
    public MyReturn updateOneself(Userinfo userinfo){

        String s = userinfoService.selectUpdate(userinfo.getLoginName(), userinfo.getUserId());
        userinfo.setUpdateTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())));
        userinfo.setUpdateBy(userinfo.getLoginName());
        System.out.println(userinfo.toString());
        if(s!=null){
            myReturn.setCode(200);
            myReturn.setMsg("该用户名字已经被使用，请换一个用户名");
            return myReturn;
        }else{
            boolean state = userinfoService.updateOneself(userinfo);
            if(state){
                return super.getSuccessResult(myReturn);
            }else{
                return super.getFailResult(myReturn);
            }
        }
    }
}
